<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            li {
                line-height: 100px;
                height: 100px;
            }
        </style>
    </head>
    <body>
        <script>
            function Person(name, age, job) {
                this.name = name;
                this.age = age;
                this.job = job;
                this.sayName = function () {
                    console.log(this.name);
                };
            }

            /*
             * 1.创建一个空对象
             * 2.链接到原型
             * 3.绑定this值
             * 4.返回新对象
             */
            // 第一种实现

            function createNew() {
                let obj = {}; // 1.创建一个空对象

                let Foo = [].shift.call(arguments);
                // let [Foo,...args] = [...arguments]

                obj.__proto__ = Foo.prototype; // 2.链接到原型

                let result = Foo.apply(obj, arguments); // 3.绑定this值 将 Obj作为fn的this，继承其属性，并获取返回结果为result
                // let result = Foo.apply(obj, args)

                return typeof result === 'object' ? result : obj; // 4.返回新对象
            }

            // myNew(Person, "Nicholas", 29, "developer")
            function myNew() {
                console.log('arguments ', arguments);

                var func = Array.prototype.shift.call(arguments);
                console.log('func ', func);

                var obj = Object.create(func.prototype);
                console.log('obj ', obj);

                var result = func.apply(obj, arguments);
                console.log('result ', result);

                return result instanceof Object ? result : obj;
            }

            // var person = new Person("Nicholas", 29, "developer");
            var person = myNew(Person, 'Nicholas', 29, 'developer');

            console.log(person.name); // Nicholas
            person.sayName(); // Nicholas
            console.log(person.__proto__ === Person.prototype); // true
        </script>
    </body>
</html>
